home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / awksrc.zip / GAWK-D~1.14 / GAWK~7.INF (.txt) < prev    next >
GNU Info File  |  1993-10-03  |  50KB  |  927 lines

  1. This is Info file gawk.info, produced by Makeinfo-1.47 from the input
  2. file gawk.texi.
  3.    This file documents `awk', a program that you can use to select
  4. particular records in a file and perform operations upon them.
  5.    This is Edition 0.14 of `The GAWK Manual',
  6. for the 2.14 version of the GNU implementation
  7. of AWK.
  8.    Copyright (C) 1989, 1991, 1992 Free Software Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: gawk.info,  Node: Time Functions,  Prev: I/O Functions,  Up: Built-in
  21. Functions for Dealing with Time Stamps
  22. ======================================
  23.    A common use for `awk' programs is the processing of log files. Log
  24. files often contain time stamp information, indicating when a
  25. particular log record was written.  Many programs log their time stamp
  26. in the form returned by the `time' system call, which is the number of
  27. seconds since a particular epoch.  On POSIX systems, it is the number
  28. of seconds since Midnight, January 1, 1970, UTC.
  29.    In order to make it easier to process such log files, and to easily
  30. produce useful reports, `gawk' provides two functions for working with
  31. time stamps.  Both of these are `gawk' extensions; they are not
  32. specified in the POSIX standard, nor are they in any other known version
  33. of `awk'.
  34. `systime()'
  35.      This function returns the current time as the number of seconds
  36.      since the system epoch.  On POSIX systems, this is the number of
  37.      seconds since Midnight, January 1, 1970, UTC.  It may be a
  38.      different number on other systems.
  39. `strftime(FORMAT, TIMESTAMP)'
  40.      This function returns a string.  It is similar to the function of
  41.      the same name in the ANSI C standard library.  The time specified
  42.      by TIMESTAMP is used to produce a string, based on the contents of
  43.      the FORMAT string.
  44.    The `systime' function allows you to compare a time stamp from a log
  45. file with the current time of day.  In particular, it is easy to
  46. determine how long ago a particular record was logged.  It also allows
  47. you to produce log records using the "seconds since the epoch" format.
  48.    The `strftime' function allows you to easily turn a time stamp into
  49. human-readable information.  It is similar in nature to the `sprintf'
  50. function, copying non-format specification characters verbatim to the
  51. returned string, and substituting date and time values for format
  52. specifications in the FORMAT string.  If no TIMESTAMP argument is
  53. supplied, `gawk' will use the current time of day as the time stamp.
  54.    `strftime' is guaranteed by the ANSI C standard to support the
  55. following date format specifications:
  56.      The locale's abbreviated weekday name.
  57.      The locale's full weekday name.
  58.      The locale's abbreviated month name.
  59.      The locale's full month name.
  60.      The locale's "appropriate" date and time representation.
  61.      The day of the month as a decimal number (01--31).
  62.      The hour (24-hour clock) as a decimal number (00--23).
  63.      The hour (12-hour clock) as a decimal number (01--12).
  64.      The day of the year as a decimal number (001--366).
  65.      The month as a decimal number (01--12).
  66.      The minute as a decimal number (00--59).
  67.      The locale's equivalent of the AM/PM designations associated with
  68.      a 12-hour clock.
  69.      The second as a decimal number (00--61).  (Occasionally there are
  70.      minutes in a year with one or two leap seconds, which is why the
  71.      seconds can go from 0 all the way to 61.)
  72.      The week number of the year (the first Sunday as the first day of
  73.      week 1) as a decimal number (00--53).
  74.      The weekday as a decimal number (0--6).  Sunday is day 0.
  75.      The week number of the year (the first Monday as the first day of
  76.      week 1) as a decimal number (00--53).
  77.      The locale's "appropriate" date representation.
  78.      The locale's "appropriate" time representation.
  79.      The year without century as a decimal number (00--99).
  80.      The year with century as a decimal number.
  81.      The time zone name or abbreviation, or no characters if no time
  82.      zone is determinable.
  83.      A literal `%'.
  84.    If a conversion specifier is not one of the above, the behavior is
  85. undefined. (1)
  86.    Informally, a "locale" is the geographic place in which a program is
  87. meant to run.  For example, a common way to abbreviate the date
  88. September 4, 1991 in the United States would be "9/4/91". In many
  89. countries in Europe, however, it would be abbreviated "4.9.91". Thus,
  90. the `%x' specification in a `"US"' locale might produce `9/4/91', while
  91. in a `"EUROPE"' locale, it might produce `4.9.91'.  The ANSI C standard
  92. defines a default `"C"' locale, which is an environment that is typical
  93. of what most C programmers are used to.
  94.    A public-domain C version of `strftime' is shipped with `gawk' for
  95. systems that are not yet fully ANSI-compliant.  If that version is used
  96. to compile `gawk' (*note Installing `gawk': Installation.), then the
  97. following additional format specifications are available:
  98.      Equivalent to specifying `%m/%d/%y'.
  99.      The day of the month, padded with a blank if it is only one digit.
  100.      Equivalent to `%b', above.
  101.      A newline character (ASCII LF).
  102.      Equivalent to specifying `%I:%M:%S %p'.
  103.      Equivalent to specifying `%H:%M'.
  104.      Equivalent to specifying `%H:%M:%S'.
  105.      A TAB character.
  106.      The century, as a number between 00 and 99.
  107.      is replaced by the weekday as a decimal number [1 (Monday)--7].
  108.      is replaced by the week number of the year (the first Monday as
  109.      the first day of week 1) as a decimal number (01--53). The method
  110.      for determining the week number is as specified by ISO 8601 (to
  111.      wit: if the week containing January 1 has four or more days in the
  112.      new year, then it is week 1, otherwise it is week 53 of the
  113.      previous year and the next week is week 1).
  114. `%Ec %EC %Ex %Ey %EY %Od %Oe %OH %OI'
  115. `%Om %OM %OS %Ou %OU %OV %Ow %OW %Oy'
  116.      These are "alternate representations" for the specifications that
  117.      use only the second letter (`%c', `%C', and so on). They are
  118.      recognized, but their normal representations are used. (These
  119.      facilitate compliance with the POSIX `date' utility.)
  120.      The date in VMS format (e.g. 20-JUN-1991).
  121.    Here are two examples that use `strftime'.  The first is an `awk'
  122. version of the C `ctime' function.  (This is a user defined function,
  123. which we have not discussed yet. *Note User-defined Functions:
  124. User-defined, for more information.)
  125.      # ctime.awk
  126.      #
  127.      # awk version of C ctime(3) function
  128.      
  129.      function ctime(ts,    format)
  130.      {
  131.          format = "%a %b %e %H:%M:%S %Z %Y"
  132.          if (ts == 0)
  133.              ts = systime()         # use current time as default
  134.          return strftime(format, ts)
  135.      }
  136.    This next example is an `awk' implementation of the POSIX `date'
  137. utility.  Normally, the `date' utility prints the current date and time
  138. of day in a well known format.  However, if you provide an argument to
  139. it that begins with a `+', `date' will copy non-format specifier
  140. characters to the standard output, and will interpret the current time
  141. according to the format specifiers in the string.  For example:
  142.      date '+Today is %A, %B %d, %Y.'
  143. might print
  144.      Today is Thursday, July 11, 1991.
  145.    Here is the `awk' version of the `date' utility.
  146.      #! /usr/bin/gawk -f
  147.      #
  148.      # date --- implement the P1003.2 Draft 11 'date' command
  149.      #
  150.      # Bug: does not recognize the -u argument.
  151.      
  152.      BEGIN    \
  153.      {
  154.          format = "%a %b %e %H:%M:%S %Z %Y"
  155.          exitval = 0
  156.      
  157.          if (ARGC > 2)
  158.              exitval = 1
  159.          else if (ARGC == 2) {
  160.              format = ARGV[1]
  161.              if (format ~ /^\+/)
  162.                  format = substr(format, 2)    # remove leading +
  163.          }
  164.          print strftime(format)
  165.          exit exitval
  166.      }
  167.    ---------- Footnotes ----------
  168.    (1)  This is because the ANSI standard for C leaves the behavior of
  169. the C version of `strftime' undefined, and `gawk' will use the system's
  170. version of `strftime' if it's there.  Typically, the conversion
  171. specifier will either not appear in the returned string, or it will
  172. appear literally.
  173. File: gawk.info,  Node: User-defined,  Next: Built-in Variables,  Prev: Built-in,  Up: Top
  174. User-defined Functions
  175. **********************
  176.    Complicated `awk' programs can often be simplified by defining your
  177. own functions.  User-defined functions can be called just like built-in
  178. ones (*note Function Calls::.), but it is up to you to define them--to
  179. tell `awk' what they should do.
  180. * Menu:
  181. * Definition Syntax::           How to write definitions and what they mean.
  182. * Function Example::            An example function definition and
  183.                                 what it does.
  184. * Function Caveats::            Things to watch out for.
  185. * Return Statement::            Specifying the value a function returns.
  186. File: gawk.info,  Node: Definition Syntax,  Next: Function Example,  Prev: User-defined,  Up: User-defined
  187. Syntax of Function Definitions
  188. ==============================
  189.    Definitions of functions can appear anywhere between the rules of the
  190. `awk' program.  Thus, the general form of an `awk' program is extended
  191. to include sequences of rules *and* user-defined function definitions.
  192.    The definition of a function named NAME looks like this:
  193.      function NAME (PARAMETER-LIST) {
  194.           BODY-OF-FUNCTION
  195.      }
  196. NAME is the name of the function to be defined.  A valid function name
  197. is like a valid variable name: a sequence of letters, digits and
  198. underscores, not starting with a digit.  Functions share the same pool
  199. of names as variables and arrays.
  200.    PARAMETER-LIST is a list of the function's arguments and local
  201. variable names, separated by commas.  When the function is called, the
  202. argument names are used to hold the argument values given in the call. 
  203. The local variables are initialized to the null string.
  204.    The BODY-OF-FUNCTION consists of `awk' statements.  It is the most
  205. important part of the definition, because it says what the function
  206. should actually *do*.  The argument names exist to give the body a way
  207. to talk about the arguments; local variables, to give the body places
  208. to keep temporary values.
  209.    Argument names are not distinguished syntactically from local
  210. variable names; instead, the number of arguments supplied when the
  211. function is called determines how many argument variables there are. 
  212. Thus, if three argument values are given, the first three names in
  213. PARAMETER-LIST are arguments, and the rest are local variables.
  214.    It follows that if the number of arguments is not the same in all
  215. calls to the function, some of the names in PARAMETER-LIST may be
  216. arguments on some occasions and local variables on others.  Another way
  217. to think of this is that omitted arguments default to the null string.
  218.    Usually when you write a function you know how many names you intend
  219. to use for arguments and how many you intend to use as locals.  By
  220. convention, you should write an extra space between the arguments and
  221. the locals, so other people can follow how your function is supposed to
  222. be used.
  223.    During execution of the function body, the arguments and local
  224. variable values hide or "shadow" any variables of the same names used
  225. in the rest of the program.  The shadowed variables are not accessible
  226. in the function definition, because there is no way to name them while
  227. their names have been taken away for the local variables.  All other
  228. variables used in the `awk' program can be referenced or set normally
  229. in the function definition.
  230.    The arguments and local variables last only as long as the function
  231. body is executing.  Once the body finishes, the shadowed variables come
  232. back.
  233.    The function body can contain expressions which call functions.  They
  234. can even call this function, either directly or by way of another
  235. function.  When this happens, we say the function is "recursive".
  236.    There is no need in `awk' to put the definition of a function before
  237. all uses of the function.  This is because `awk' reads the entire
  238. program before starting to execute any of it.
  239.    In many `awk' implementations, the keyword `function' may be
  240. abbreviated `func'.  However, POSIX only specifies the use of the
  241. keyword `function'.  This actually has some practical implications. If
  242. `gawk' is in POSIX-compatibility mode (*note Invoking `awk': Command
  243. Line.), then the following statement will *not* define a function:
  244.      func foo() { a = sqrt($1) ; print a }
  245. Instead it defines a rule that, for each record, concatenates the value
  246. of the variable `func' with the return value of the function `foo', and
  247. based on the truth value of the result, executes the corresponding
  248. action. This is probably not what was desired.  (`awk' accepts this
  249. input as syntactically valid, since functions may be used before they
  250. are defined in `awk' programs.)
  251. File: gawk.info,  Node: Function Example,  Next: Function Caveats,  Prev: Definition Syntax,  Up: User-defined
  252. Function Definition Example
  253. ===========================
  254.    Here is an example of a user-defined function, called `myprint', that
  255. takes a number and prints it in a specific format.
  256.      function myprint(num)
  257.      {
  258.           printf "%6.3g\n", num
  259.      }
  260. To illustrate, here is an `awk' rule which uses our `myprint' function:
  261.      $3 > 0     { myprint($3) }
  262. This program prints, in our special format, all the third fields that
  263. contain a positive number in our input.  Therefore, when given:
  264.       1.2   3.4    5.6   7.8
  265.       9.10 11.12 -13.14 15.16
  266.      17.18 19.20  21.22 23.24
  267. this program, using our function to format the results, prints:
  268.         5.6
  269.        21.2
  270.    Here is a rather contrived example of a recursive function.  It
  271. prints a string backwards:
  272.      function rev (str, len) {
  273.          if (len == 0) {
  274.              printf "\n"
  275.              return
  276.          }
  277.          printf "%c", substr(str, len, 1)
  278.          rev(str, len - 1)
  279.      }
  280. File: gawk.info,  Node: Function Caveats,  Next: Return Statement,  Prev: Function Example,  Up: User-defined
  281. Calling User-defined Functions
  282. ==============================
  283.    "Calling a function" means causing the function to run and do its
  284. job. A function call is an expression, and its value is the value
  285. returned by the function.
  286.    A function call consists of the function name followed by the
  287. arguments in parentheses.  What you write in the call for the arguments
  288. are `awk' expressions; each time the call is executed, these
  289. expressions are evaluated, and the values are the actual arguments.  For
  290. example, here is a call to `foo' with three arguments (the first being
  291. a string concatenation):
  292.      foo(x y, "lose", 4 * z)
  293.      *Caution:* whitespace characters (spaces and tabs) are not allowed
  294.      between the function name and the open-parenthesis of the argument
  295.      list. If you write whitespace by mistake, `awk' might think that
  296.      you mean to concatenate a variable with an expression in
  297.      parentheses.  However, it notices that you used a function name
  298.      and not a variable name, and reports an error.
  299.    When a function is called, it is given a *copy* of the values of its
  300. arguments.  This is called "call by value".  The caller may use a
  301. variable as the expression for the argument, but the called function
  302. does not know this: it only knows what value the argument had.  For
  303. example, if you write this code:
  304.      foo = "bar"
  305.      z = myfunc(foo)
  306. then you should not think of the argument to `myfunc' as being "the
  307. variable `foo'."  Instead, think of the argument as the string value,
  308. `"bar"'.
  309.    If the function `myfunc' alters the values of its local variables,
  310. this has no effect on any other variables.  In particular, if `myfunc'
  311. does this:
  312.      function myfunc (win) {
  313.        print win
  314.        win = "zzz"
  315.        print win
  316.      }
  317. to change its first argument variable `win', this *does not* change the
  318. value of `foo' in the caller.  The role of `foo' in calling `myfunc'
  319. ended when its value, `"bar"', was computed. If `win' also exists
  320. outside of `myfunc', the function body cannot alter this outer value,
  321. because it is shadowed during the execution of `myfunc' and cannot be
  322. seen or changed from there.
  323.    However, when arrays are the parameters to functions, they are *not*
  324. copied.  Instead, the array itself is made available for direct
  325. manipulation by the function.  This is usually called "call by
  326. reference". Changes made to an array parameter inside the body of a
  327. function *are* visible outside that function. This can be *very*
  328. dangerous if you do not watch what you are doing.  For example:
  329.      function changeit (array, ind, nvalue) {
  330.           array[ind] = nvalue
  331.      }
  332.      
  333.      BEGIN {
  334.                 a[1] = 1 ; a[2] = 2 ; a[3] = 3
  335.                 changeit(a, 2, "two")
  336.                 printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3]
  337.            }
  338. prints `a[1] = 1, a[2] = two, a[3] = 3', because calling `changeit'
  339. stores `"two"' in the second element of `a'.
  340. File: gawk.info,  Node: Return Statement,  Prev: Function Caveats,  Up: User-defined
  341. The `return' Statement
  342. ======================
  343.    The body of a user-defined function can contain a `return' statement.
  344. This statement returns control to the rest of the `awk' program.  It
  345. can also be used to return a value for use in the rest of the `awk'
  346. program.  It looks like this:
  347.      return EXPRESSION
  348.    The EXPRESSION part is optional.  If it is omitted, then the returned
  349. value is undefined and, therefore, unpredictable.
  350.    A `return' statement with no value expression is assumed at the end
  351. of every function definition.  So if control reaches the end of the
  352. function body, then the function returns an unpredictable value.  `awk'
  353. will not warn you if you use the return value of such a function; you
  354. will simply get unpredictable or unexpected results.
  355.    Here is an example of a user-defined function that returns a value
  356. for the largest number among the elements of an array:
  357.      function maxelt (vec,   i, ret) {
  358.           for (i in vec) {
  359.                if (ret == "" || vec[i] > ret)
  360.                     ret = vec[i]
  361.           }
  362.           return ret
  363.      }
  364. You call `maxelt' with one argument, which is an array name.  The local
  365. variables `i' and `ret' are not intended to be arguments; while there
  366. is nothing to stop you from passing two or three arguments to `maxelt',
  367. the results would be strange.  The extra space before `i' in the
  368. function parameter list is to indicate that `i' and `ret' are not
  369. supposed to be arguments.  This is a convention which you should follow
  370. when you define functions.
  371.    Here is a program that uses our `maxelt' function.  It loads an
  372. array, calls `maxelt', and then reports the maximum number in that
  373. array:
  374.      awk '
  375.      function maxelt (vec,   i, ret) {
  376.           for (i in vec) {
  377.                if (ret == "" || vec[i] > ret)
  378.                     ret = vec[i]
  379.           }
  380.           return ret
  381.      }
  382.      
  383.      # Load all fields of each record into nums.
  384.      {
  385.                for(i = 1; i <= NF; i++)
  386.                     nums[NR, i] = $i
  387.      }
  388.      
  389.      END {
  390.           print maxelt(nums)
  391.      }'
  392.    Given the following input:
  393.       1 5 23 8 16
  394.      44 3 5 2 8 26
  395.      256 291 1396 2962 100
  396.      -6 467 998 1101
  397.      99385 11 0 225
  398. our program tells us (predictably) that:
  399.      99385
  400. is the largest number in our array.
  401. File: gawk.info,  Node: Built-in Variables,  Next: Command Line,  Prev: User-defined,  Up: Top
  402. Built-in Variables
  403. ******************
  404.    Most `awk' variables are available for you to use for your own
  405. purposes; they never change except when your program assigns values to
  406. them, and never affect anything except when your program examines them.
  407.    A few variables have special built-in meanings.  Some of them `awk'
  408. examines automatically, so that they enable you to tell `awk' how to do
  409. certain things.  Others are set automatically by `awk', so that they
  410. carry information from the internal workings of `awk' to your program.
  411.    This chapter documents all the built-in variables of `gawk'.  Most
  412. of them are also documented in the chapters where their areas of
  413. activity are described.
  414. * Menu:
  415. * User-modified::               Built-in variables that you change
  416.                                 to control `awk'.
  417. * Auto-set::                    Built-in variables where `awk'
  418.                                 gives you information.
  419. File: gawk.info,  Node: User-modified,  Next: Auto-set,  Prev: Built-in Variables,  Up: Built-in Variables
  420. Built-in Variables that Control `awk'
  421. =====================================
  422.    This is a list of the variables which you can change to control how
  423. `awk' does certain things.
  424. `CONVFMT'
  425.      This string is used by `awk' to control conversion of numbers to
  426.      strings (*note Conversion of Strings and Numbers: Conversion.). It
  427.      works by being passed, in effect, as the first argument to the
  428.      `sprintf' function.  Its default value is `"%.6g"'. `CONVFMT' was
  429.      introduced by the POSIX standard.
  430. `FIELDWIDTHS'
  431.      This is a space separated list of columns that tells `gawk' how to
  432.      manage input with fixed, columnar boundaries.  It is an
  433.      experimental feature that is still evolving.  Assigning to
  434.      `FIELDWIDTHS' overrides the use of `FS' for field splitting. *Note
  435.      Reading Fixed-width Data: Constant Size, for more information.
  436.      If `gawk' is in compatibility mode (*note Invoking `awk': Command
  437.      Line.), then `FIELDWIDTHS' has no special meaning, and field
  438.      splitting operations are done based exclusively on the value of
  439.      `FS'.
  440.      `FS' is the input field separator (*note Specifying how Fields are
  441.      Separated: Field Separators.). The value is a single-character
  442.      string or a multi-character regular expression that matches the
  443.      separations between fields in an input record.
  444.      The default value is `" "', a string consisting of a single space.
  445.       As a special exception, this value actually means that any
  446.      sequence of spaces and tabs is a single separator.  It also causes
  447.      spaces and tabs at the beginning or end of a line to be ignored.
  448.      You can set the value of `FS' on the command line using the `-F'
  449.      option:
  450.           awk -F, 'PROGRAM' INPUT-FILES
  451.      If `gawk' is using `FIELDWIDTHS' for field-splitting, assigning a
  452.      value to `FS' will cause `gawk' to return to the normal,
  453.      regexp-based, field splitting.
  454. `IGNORECASE'
  455.      If `IGNORECASE' is nonzero, then *all* regular expression matching
  456.      is done in a case-independent fashion.  In particular, regexp
  457.      matching with `~' and `!~', and the `gsub' `index', `match',
  458.      `split' and `sub' functions all ignore case when doing their
  459.      particular regexp operations.  *Note:* since field splitting with
  460.      the value of the `FS' variable is also a regular expression
  461.      operation, that too is done with case ignored. *Note
  462.      Case-sensitivity in Matching: Case-sensitivity.
  463.      If `gawk' is in compatibility mode (*note Invoking `awk': Command
  464.      Line.), then `IGNORECASE' has no special meaning, and regexp
  465.      operations are always case-sensitive.
  466. `OFMT'
  467.      This string is used by `awk' to control conversion of numbers to
  468.      strings (*note Conversion of Strings and Numbers: Conversion.) for
  469.      printing with the `print' statement. It works by being passed, in
  470.      effect, as the first argument to the `sprintf' function.  Its
  471.      default value is `"%.6g"'. Earlier versions of `awk' also used
  472.      `OFMT' to specify the format for converting numbers to strings in
  473.      general expressions; this has been taken over by `CONVFMT'.
  474. `OFS'
  475.      This is the output field separator (*note Output Separators::.). 
  476.      It is output between the fields output by a `print' statement.  Its
  477.      default value is `" "', a string consisting of a single space.
  478. `ORS'
  479.      This is the output record separator.  It is output at the end of
  480.      every `print' statement.  Its default value is a string containing
  481.      a single newline character, which could be written as `"\n"'.
  482.      (*Note Output Separators::.)
  483.      This is `awk''s input record separator.  Its default value is a
  484.      string containing a single newline character, which means that an
  485.      input record consists of a single line of text. (*Note How Input
  486.      is Split into Records: Records.)
  487. `SUBSEP'
  488.      `SUBSEP' is the subscript separator.  It has the default value of
  489.      `"\034"', and is used to separate the parts of the name of a
  490.      multi-dimensional array.  Thus, if you access `foo[12,3]', it
  491.      really accesses `foo["12\0343"]' (*note Multi-dimensional Arrays:
  492.      Multi-dimensional.).
  493. File: gawk.info,  Node: Auto-set,  Prev: User-modified,  Up: Built-in Variables
  494. Built-in Variables that Convey Information
  495. ==========================================
  496.    This is a list of the variables that are set automatically by `awk'
  497. on certain occasions so as to provide information to your program.
  498. `ARGC'
  499. `ARGV'
  500.      The command-line arguments available to `awk' programs are stored
  501.      in an array called `ARGV'.  `ARGC' is the number of command-line
  502.      arguments present.  *Note Invoking `awk': Command Line. `ARGV' is
  503.      indexed from zero to `ARGC - 1'.  For example:
  504.           awk 'BEGIN { for (i = 0; i < ARGC; i++)
  505.                              print ARGV[i] }' inventory-shipped BBS-list
  506.      In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
  507.      `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.  The
  508.      value of `ARGC' is 3, one more than the index of the last element
  509.      in `ARGV' since the elements are numbered from zero.
  510.      The names `ARGC' and `ARGV', as well the convention of indexing
  511.      the array from 0 to `ARGC - 1', are derived from the C language's
  512.      method of accessing command line arguments.
  513.      Notice that the `awk' program is not entered in `ARGV'.  The other
  514.      special command line options, with their arguments, are also not
  515.      entered.  But variable assignments on the command line *are*
  516.      treated as arguments, and do show up in the `ARGV' array.
  517.      Your program can alter `ARGC' and the elements of `ARGV'. Each
  518.      time `awk' reaches the end of an input file, it uses the next
  519.      element of `ARGV' as the name of the next input file.  By storing a
  520.      different string there, your program can change which files are
  521.      read. You can use `"-"' to represent the standard input.  By
  522.      storing additional elements and incrementing `ARGC' you can cause
  523.      additional files to be read.
  524.      If you decrease the value of `ARGC', that eliminates input files
  525.      from the end of the list.  By recording the old value of `ARGC'
  526.      elsewhere, your program can treat the eliminated arguments as
  527.      something other than file names.
  528.      To eliminate a file from the middle of the list, store the null
  529.      string (`""') into `ARGV' in place of the file's name.  As a
  530.      special feature, `awk' ignores file names that have been replaced
  531.      with the null string.
  532. `ENVIRON'
  533.      This is an array that contains the values of the environment.  The
  534.      array indices are the environment variable names; the values are
  535.      the values of the particular environment variables.  For example,
  536.      `ENVIRON["HOME"]' might be `/u/close'.  Changing this array does
  537.      not affect the environment passed on to any programs that `awk'
  538.      may spawn via redirection or the `system' function. (In a future
  539.      version of `gawk', it may do so.)
  540.      Some operating systems may not have environment variables. On such
  541.      systems, the array `ENVIRON' is empty.
  542. `FILENAME'
  543.      This is the name of the file that `awk' is currently reading. If
  544.      `awk' is reading from the standard input (in other words, there
  545.      are no files listed on the command line), `FILENAME' is set to
  546.      `"-"'. `FILENAME' is changed each time a new file is read (*note
  547.      Reading Input Files: Reading Files.).
  548. `FNR'
  549.      `FNR' is the current record number in the current file.  `FNR' is
  550.      incremented each time a new record is read (*note Explicit Input
  551.      with `getline': Getline.).  It is reinitialized to 0 each time a
  552.      new input file is started.
  553.      `NF' is the number of fields in the current input record. `NF' is
  554.      set each time a new record is read, when a new field is created,
  555.      or when `$0' changes (*note Examining Fields: Fields.).
  556.      This is the number of input records `awk' has processed since the
  557.      beginning of the program's execution. (*note How Input is Split
  558.      into Records: Records.). `NR' is set each time a new record is
  559.      read.
  560. `RLENGTH'
  561.      `RLENGTH' is the length of the substring matched by the `match'
  562.      function (*note Built-in Functions for String Manipulation: String
  563.      Functions.). `RLENGTH' is set by invoking the `match' function. 
  564.      Its value is the length of the matched string, or -1 if no match
  565.      was found.
  566. `RSTART'
  567.      `RSTART' is the start-index in characters of the substring matched
  568.      by the `match' function (*note Built-in Functions for String
  569.      Manipulation: String Functions.). `RSTART' is set by invoking the
  570.      `match' function.  Its value is the position of the string where
  571.      the matched substring starts, or 0 if no match was found.
  572. File: gawk.info,  Node: Command Line,  Next: Language History,  Prev: Built-in Variables,  Up: Top
  573. Invoking `awk'
  574. **************
  575.    There are two ways to run `awk': with an explicit program, or with
  576. one or more program files.  Here are templates for both of them; items
  577. enclosed in `[...]' in these templates are optional.
  578.      awk [`-FFS'] [`-W' GAWK-OPTS] [`-v VAR=VAL'] [`--'] 'PROGRAM' FILE ...
  579.      awk [`-FFS'] [`-W' GAWK-OPTS] [`-v VAR=VAL'] `-f SOURCE-FILE'
  580.            [`-f SOURCE-FILE ...'] [`--'] FILE ...
  581. * Menu:
  582. * Options::                     Command line options and their meanings.
  583. * Other Arguments::             Input file names and variable assignments.
  584. * AWKPATH Variable::            Searching directories for `awk' programs.
  585. * Obsolete::                    Obsolete Options and/or features.
  586. * Undocumented::                Undocumented Options and Features.
  587. File: gawk.info,  Node: Options,  Next: Other Arguments,  Prev: Command Line,  Up: Command Line
  588. Command Line Options
  589. ====================
  590.    Options begin with a minus sign, and consist of a single character.
  591. The options and their meanings are as follows:
  592. `-FFS'
  593.      Sets the `FS' variable to FS (*note Specifying how Fields are
  594.      Separated: Field Separators.).
  595. `-f SOURCE-FILE'
  596.      Indicates that the `awk' program is to be found in SOURCE-FILE
  597.      instead of in the first non-option argument.
  598. `-v VAR=VAL'
  599.      Sets the variable VAR to the value VAL *before* execution of the
  600.      program begins.  Such variable values are available inside the
  601.      `BEGIN' rule (see below for a fuller explanation).
  602.      The `-v' option can only set one variable, but you can use it more
  603.      than once, setting another variable each time, like this:
  604.      `-v foo=1 -v bar=2'.
  605. `-W GAWK-OPT'
  606.      Following the POSIX standard, options that are specific to `gawk'
  607.      are supplied as arguments to the `-W' option.  These arguments may
  608.      be separated by commas, or quoted and separated by whitespace.
  609.      Case is ignored when processing these options.  The following
  610.      options are available:
  611.     `compat'
  612.           Specifies "compatibility mode", in which the GNU extensions in
  613.           `gawk' are disabled, so that `gawk' behaves just like Unix
  614.           `awk'. *Note Extensions in `gawk' not in POSIX `awk':
  615.           POSIX/GNU, which summarizes the extensions.  Also see *Note
  616.           Downward Compatibility and Debugging: Compatibility Mode.
  617.     `lint'
  618.           Provide warnings about constructs that are dubious or
  619.           non-portable to other `awk' implementations.
  620.     `copyleft'
  621.     `copyright'
  622.           Print the short version of the General Public License. This
  623.           option may disappear in a future version of `gawk'.
  624.     `posix'
  625.           Operate in strict POSIX mode.  This disables all `gawk'
  626.           extensions (just like `compat'), and adds the following
  627.           additional restrictions:
  628.              * `\x' escape sequences are not recognized (*note Constant
  629.                Expressions: Constants.).
  630.              * The synonym `func' for the keyword `function' is not
  631.                recognized (*note Syntax of Function Definitions:
  632.                Definition Syntax.).
  633.              * The operators `**' and `**=' cannot be used in place of
  634.                `^' and `^=' (*note Arithmetic Operators: Arithmetic
  635.                Ops., and also *note Assignment Expressions: Assignment
  636.                Ops.).
  637.              * Specifying `-Ft' on the command line does not set the
  638.                value of `FS' to be a single tab character (*note
  639.                Specifying how Fields are Separated: Field Separators.).
  640.           Although you can supply both `-W compat' and `-W posix' on the
  641.           command line, `-W posix' will take precedence.
  642.     `version'
  643.           Prints version information for this particular copy of `gawk'.
  644.           This is so you can determine if your copy of `gawk' is up to
  645.           date with respect to whatever the Free Software Foundation is
  646.           currently distributing.  This option may disappear in a
  647.           future version of `gawk'.
  648.      Signals the end of the command line options.  The following
  649.      arguments are not treated as options even if they begin with `-'. 
  650.      This interpretation of `--' follows the POSIX argument parsing
  651.      conventions.
  652.      This is useful if you have file names that start with `-', or in
  653.      shell scripts, if you have file names that will be specified by
  654.      the user which could start with `-'.
  655.    The `-a', `-e', `-c', `-C', and `-V' options of `gawk' version
  656. 2.11.1 are recognized, but produce a warning message.  They will go
  657. away in the next major release of `gawk'.
  658.    Any other options are flagged as invalid with a warning message, but
  659. are otherwise ignored.
  660.    In compatibility mode, as a special case, if the value of FS supplied
  661. to the `-F' option is `t', then `FS' is set to the tab character
  662. (`"\t"').  This is only true for `-W compat', and not for `-W posix'
  663. (*note Specifying how Fields are Separated: Field Separators.).
  664.    If the `-f' option is *not* used, then the first non-option command
  665. line argument is expected to be the program text.
  666.    The `-f' option may be used more than once on the command line. Then
  667. `awk' reads its program source from all of the named files, as if they
  668. had been concatenated together into one big file.  This is useful for
  669. creating libraries of `awk' functions.  Useful functions can be written
  670. once, and then retrieved from a standard place, instead of having to be
  671. included into each individual program.  You can still type in a program
  672. at the terminal and use library functions, by specifying `-f /dev/tty'.
  673.  `awk' will read a file from the terminal to use as part of the `awk'
  674. program.  After typing your program, type `Control-d' (the end-of-file
  675. character) to terminate it. (You may also use `-f -' to read program
  676. source from the standard input, but then you will not be able to also
  677. use the standard input as a source of data.)
  678. File: gawk.info,  Node: Other Arguments,  Next: AWKPATH Variable,  Prev: Options,  Up: Command Line
  679. Other Command Line Arguments
  680. ============================
  681.    Any additional arguments on the command line are normally treated as
  682. input files to be processed in the order specified.  However, an
  683. argument that has the form `VAR=VALUE', means to assign the value VALUE
  684. to the variable VAR--it does not specify a file at all.
  685.    All these arguments are made available to your `awk' program in the
  686. `ARGV' array (*note Built-in Variables::.).  Command line options and
  687. the program text (if present) are omitted from the `ARGV' array.  All
  688. other arguments, including variable assignments, are included.
  689.    The distinction between file name arguments and variable-assignment
  690. arguments is made when `awk' is about to open the next input file. At
  691. that point in execution, it checks the "file name" to see whether it is
  692. really a variable assignment; if so, `awk' sets the variable instead of
  693. reading a file.
  694.    Therefore, the variables actually receive the specified values after
  695. all previously specified files have been read.  In particular, the
  696. values of variables assigned in this fashion are *not* available inside
  697. a `BEGIN' rule (*note `BEGIN' and `END' Special Patterns: BEGIN/END.),
  698. since such rules are run before `awk' begins scanning the argument list.
  699. The values given on the command line are processed for escape sequences
  700. (*note Constant Expressions: Constants.).
  701.    In some earlier implementations of `awk', when a variable assignment
  702. occurred before any file names, the assignment would happen *before*
  703. the `BEGIN' rule was executed.  Some applications came to depend upon
  704. this "feature."  When `awk' was changed to be more consistent, the `-v'
  705. option was added to accommodate applications that depended upon this
  706. old behavior.
  707.    The variable assignment feature is most useful for assigning to
  708. variables such as `RS', `OFS', and `ORS', which control input and
  709. output formats, before scanning the data files.  It is also useful for
  710. controlling state if multiple passes are needed over a data file.  For
  711. example:
  712.      awk 'pass == 1  { PASS 1 STUFF }
  713.           pass == 2  { PASS 2 STUFF }' pass=1 datafile pass=2 datafile
  714.    Given the variable assignment feature, the `-F' option is not
  715. strictly necessary.  It remains for historical compatibility.
  716. File: gawk.info,  Node: AWKPATH Variable,  Next: Obsolete,  Prev: Other Arguments,  Up: Command Line
  717. The `AWKPATH' Environment Variable
  718. ==================================
  719.    The previous section described how `awk' program files can be named
  720. on the command line with the `-f' option.  In some `awk'
  721. implementations, you must supply a precise path name for each program
  722. file, unless the file is in the current directory.
  723.    But in `gawk', if the file name supplied in the `-f' option does not
  724. contain a `/', then `gawk' searches a list of directories (called the
  725. "search path"), one by one, looking for a file with the specified name.
  726.    The search path is actually a string consisting of directory names
  727. separated by colons.  `gawk' gets its search path from the `AWKPATH'
  728. environment variable.  If that variable does not exist, `gawk' uses the
  729. default path, which is `.:/usr/lib/awk:/usr/local/lib/awk'.  (Programs
  730. written by system administrators should use an `AWKPATH' variable that
  731. does not include the current directory, `.'.)
  732.    The search path feature is particularly useful for building up
  733. libraries of useful `awk' functions.  The library files can be placed
  734. in a standard directory that is in the default path, and then specified
  735. on the command line with a short file name.  Otherwise, the full file
  736. name would have to be typed for each file.
  737.    Path searching is not done if `gawk' is in compatibility mode. This
  738. is true for both `-W compat' and `-W posix'. *Note Invoking `awk':
  739. Command Line.
  740.    *Note:* if you want files in the current directory to be found, you
  741. must include the current directory in the path, either by writing `.'
  742. as an entry in the path, or by writing a null entry in the path.  (A
  743. null entry is indicated by starting or ending the path with a colon, or
  744. by placing two colons next to each other (`::').)  If the current
  745. directory is not included in the path, then files cannot be found in
  746. the current directory.  This path search mechanism is identical to the
  747. shell's.
  748. File: gawk.info,  Node: Obsolete,  Next: Undocumented,  Prev: AWKPATH Variable,  Up: Command Line
  749. Obsolete Options and/or Features
  750. ================================
  751.    This section describes features and/or command line options from the
  752. previous release of `gawk' that are either not available in the current
  753. version, or that are still supported but deprecated (meaning that they
  754. will *not* be in the next release).
  755.    For version 2.14 of `gawk', the following command line options are
  756. recognized, but produce a warning message (*note Invoking `awk':
  757. Command Line.).
  758.      Use `-W compat' instead.
  759.      Use `-W version' instead.
  760.      Use `-W copyright' instead.
  761.      These options produce a warning message but have no effect on the
  762.      execution of `gawk'.  The POSIX standard now specifies traditional
  763.      `awk' regular expressions for the `awk' utility.
  764.    The public-domain version of `strftime' that is distributed with
  765. `gawk' changed for the 2.14 release.  The `%V' conversion specifier
  766. that used to generate the date in VMS format was changed to `%v'. This
  767. is because the POSIX standard for the `date' utility now specifies a
  768. `%V' conversion specifier. *Note Functions for Dealing with Time
  769. Stamps: Time Functions, for details.
  770. File: gawk.info,  Node: Undocumented,  Prev: Obsolete,  Up: Command Line
  771. Undocumented Options and Features
  772. =================================
  773.    This section intentionally left blank.
  774. File: gawk.info,  Node: Language History,  Next: Installation,  Prev: Command Line,  Up: Top
  775. The Evolution of the `awk' Language
  776. ***********************************
  777.    This manual describes the GNU implementation of `awk', which is
  778. patterned after the POSIX specification.  Many `awk' users are only
  779. familiar with the original `awk' implementation in Version 7 Unix,
  780. which is also the basis for the version in Berkeley Unix (through
  781. 4.3--Reno).  This chapter briefly describes the evolution of the `awk'
  782. language.
  783. * Menu:
  784. * V7/S5R3.1::                   The major changes between V7 and
  785.                                 System V Release 3.1.
  786. * S5R4::                        Minor changes between System V
  787.                                 Releases 3.1 and 4.
  788. * POSIX::                       New features from the POSIX standard.
  789. * POSIX/GNU::                   The extensions in `gawk'
  790.                                 not in POSIX `awk'.
  791. File: gawk.info,  Node: V7/S5R3.1,  Next: S5R4,  Prev: Language History,  Up: Language History
  792. Major Changes between V7 and S5R3.1
  793. ===================================
  794.    The `awk' language evolved considerably between the release of
  795. Version 7 Unix (1978) and the new version first made widely available in
  796. System V Release 3.1 (1987).  This section summarizes the changes, with
  797. cross-references to further details.
  798.    * The requirement for `;' to separate rules on a line (*note `awk'
  799.      Statements versus Lines: Statements/Lines.).
  800.    * User-defined functions, and the `return' statement (*note
  801.      User-defined Functions: User-defined.).
  802.    * The `delete' statement (*note The `delete' Statement: Delete.).
  803.    * The `do'-`while' statement (*note The `do'-`while' Statement: Do
  804.      Statement.).
  805.    * The built-in functions `atan2', `cos', `sin', `rand' and `srand'
  806.      (*note Numeric Built-in Functions: Numeric Functions.).
  807.    * The built-in functions `gsub', `sub', and `match' (*note Built-in
  808.      Functions for String Manipulation: String Functions.).
  809.    * The built-in functions `close', which closes an open file, and
  810.      `system', which allows the user to execute operating system
  811.      commands (*note Built-in Functions for Input/Output: I/O
  812.      Functions.).
  813.    * The `ARGC', `ARGV', `FNR', `RLENGTH', `RSTART', and `SUBSEP'
  814.      built-in variables (*note Built-in Variables::.).
  815.    * The conditional expression using the operators `?' and `:' (*note
  816.      Conditional Expressions: Conditional Exp.).
  817.    * The exponentiation operator `^' (*note Arithmetic Operators:
  818.      Arithmetic Ops.) and its assignment operator form `^=' (*note
  819.      Assignment Expressions: Assignment Ops.).
  820.    * C-compatible operator precedence, which breaks some old `awk'
  821.      programs (*note Operator Precedence (How Operators Nest):
  822.      Precedence.).
  823.    * Regexps as the value of `FS' (*note Specifying how Fields are
  824.      Separated: Field Separators.), and as the third argument to the
  825.      `split' function (*note Built-in Functions for String
  826.      Manipulation: String Functions.).
  827.    * Dynamic regexps as operands of the `~' and `!~' operators (*note
  828.      How to Use Regular Expressions: Regexp Usage.).
  829.    * Escape sequences (*note Constant Expressions: Constants.) in
  830.      regexps.
  831.    * The escape sequences `\b', `\f', and `\r' (*note Constant
  832.      Expressions: Constants.).
  833.    * Redirection of input for the `getline' function (*note Explicit
  834.      Input with `getline': Getline.).
  835.    * Multiple `BEGIN' and `END' rules (*note `BEGIN' and `END' Special
  836.      Patterns: BEGIN/END.).
  837.    * Simulated multi-dimensional arrays (*note Multi-dimensional
  838.      Arrays: Multi-dimensional.).
  839. File: gawk.info,  Node: S5R4,  Next: POSIX,  Prev: V7/S5R3.1,  Up: Language History
  840. Changes between S5R3.1 and S5R4
  841. ===============================
  842.    The System V Release 4 version of Unix `awk' added these features
  843. (some of which originated in `gawk'):
  844.    * The `ENVIRON' variable (*note Built-in Variables::.).
  845.    * Multiple `-f' options on the command line (*note Invoking `awk':
  846.      Command Line.).
  847.    * The `-v' option for assigning variables before program execution
  848.      begins (*note Invoking `awk': Command Line.).
  849.    * The `--' option for terminating command line options.
  850.    * The `\a', `\v', and `\x' escape sequences (*note Constant
  851.      Expressions: Constants.).
  852.    * A defined return value for the `srand' built-in function (*note
  853.      Numeric Built-in Functions: Numeric Functions.).
  854.    * The `toupper' and `tolower' built-in string functions for case
  855.      translation (*note Built-in Functions for String Manipulation:
  856.      String Functions.).
  857.    * A cleaner specification for the `%c' format-control letter in the
  858.      `printf' function (*note Using `printf' Statements for Fancier
  859.      Printing: Printf.).
  860.    * The ability to dynamically pass the field width and precision
  861.      (`"%*.*d"') in the argument list of the `printf' function (*note
  862.      Using `printf' Statements for Fancier Printing: Printf.).
  863.    * The use of constant regexps such as `/foo/' as expressions, where
  864.      they are equivalent to use of the matching operator, as in `$0 ~
  865.      /foo/' (*note Constant Expressions: Constants.).
  866. File: gawk.info,  Node: POSIX,  Next: POSIX/GNU,  Prev: S5R4,  Up: Language History
  867. Changes between S5R4 and POSIX `awk'
  868. ====================================
  869.    The POSIX Command Language and Utilities standard for `awk'
  870. introduced the following changes into the language:
  871.    * The use of `-W' for implementation-specific options.
  872.    * The use of `CONVFMT' for controlling the conversion of numbers to
  873.      strings (*note Conversion of Strings and Numbers: Conversion.).
  874.    * The concept of a numeric string, and tighter comparison rules to go
  875.      with it (*note Comparison Expressions: Comparison Ops.).
  876.    * More complete documentation of many of the previously undocumented
  877.      features of the language.
  878. File: gawk.info,  Node: POSIX/GNU,  Prev: POSIX,  Up: Language History
  879. Extensions in `gawk' not in POSIX `awk'
  880. =======================================
  881.    The GNU implementation, `gawk', adds these features:
  882.    * The `AWKPATH' environment variable for specifying a path search for
  883.      the `-f' command line option (*note Invoking `awk': Command Line.).
  884.    * The various `gawk' specific features available via the `-W'
  885.      command line option (*note Invoking `awk': Command Line.).
  886.    * The `IGNORECASE' variable and its effects (*note Case-sensitivity
  887.      in Matching: Case-sensitivity.).
  888.    * The `FIELDWIDTHS' variable and its effects (*note Reading
  889.      Fixed-width Data: Constant Size.).
  890.    * The `next file' statement for skipping to the next data file
  891.      (*note The `next file' Statement: Next File Statement.).
  892.    * The `systime' and `strftime' built-in functions for obtaining and
  893.      printing time stamps (*note Functions for Dealing with Time
  894.      Stamps: Time Functions.).
  895.    * The `/dev/stdin', `/dev/stdout', `/dev/stderr', and `/dev/fd/N'
  896.      file name interpretation (*note Standard I/O Streams: Special
  897.      Files.).
  898.    * The `-W compat' option to turn off these extensions (*note
  899.      Invoking `awk': Command Line.).
  900.    * The `-W posix' option for full POSIX compliance (*note Invoking
  901.      `awk': Command Line.).
  902. File: gawk.info,  Node: Installation,  Next: Gawk Summary,  Prev: Language History,  Up: Top
  903. Installing `gawk'
  904. *****************
  905.    This chapter provides instructions for installing `gawk' on the
  906. various platforms that are supported by the developers.  The primary
  907. developers support Unix (and one day, GNU), while the other ports were
  908. contributed.  The file `ACKNOWLEDGMENT' in the `gawk' distribution
  909. lists the electronic mail addresses of the people who did the
  910. respective ports.
  911. * Menu:
  912. * Gawk Distribution::           What is in the `gawk' distribution.
  913. * Unix Installation::           Installing `gawk' under various versions
  914.                                 of Unix.
  915. * VMS Installation::            Installing `gawk' on VMS.
  916. * MS-DOS Installation::         Installing `gawk' on MS-DOS.
  917. * Atari Installation::          Installing `gawk' on the Atari ST.
  918. File: gawk.info,  Node: Gawk Distribution,  Next: Unix Installation,  Prev: Installation,  Up: Installation
  919. The `gawk' Distribution
  920. =======================
  921.    This section first describes how to get and extract the `gawk'
  922. distribution, and then discusses what is in the various files and
  923. subdirectories.
  924. * Menu:
  925. * Extracting::                  How to get and extract the distribution.
  926. * Distribution contents::       What is in the distribution.
  927.